<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=375,initial-scale=1,maximum-scale=1,user-scalable=0">
  <title>重生魂穿古代人生模拟（沙雕版）</title>
  <style>
    :root {
      --main-grad: linear-gradient(135deg, #fff9e5 0%, #f6e5ca 60%, #f5e8ff 100%);
      --card-bg: #ffe8b4d9;
      --accent-gradient: linear-gradient(90deg, #ffb564, #ffe4ab 30%, #ffbbe0 55%, #cffcff 100%);
      --shadow: 0 4px 16px rgba(0,0,0,0.15), 0 1.5px 3.5px #ffd87b;
      --border: 2.5px solid #feba78;
      --border-radius: 25px;
      --text-main: #703704;
      --text-sub: #7b6a55;
      --bar-bg: rgba(250,174,80,0.09);
      --bar-glow: 0 0 16px 4px #ffe4b0cc;
      --zone1-bg: linear-gradient(83deg, #fff2d6d9, #ffeec77c 70%, #fde9f3ce 100%);
      --zone2-bg: linear-gradient(83deg, #e8fced, #cffcff 70%, #d7fcb3 100%);
      --zone3-bg: linear-gradient(83deg, #fff6ff, #ffe9e3 70%, #e5c3ff 100%);
      --zone4-bg: linear-gradient(83deg, #fffbe1, #fccac1 70%, #ffd0f3 100%);
      --zone5-bg: linear-gradient(83deg, #fff9e7, #b3ebff 70%, #fff7c3 100%);
      --zone6-bg: linear-gradient(83deg, #fdf5e6, #e6e6fa 70%, #fffacd 100%);
    }
    html,body {
      margin:0;padding:0;
      width:100vw;height:100vh;
      background:var(--main-grad);
      font-family:"霞鹜文楷", "苹方", "PingFang SC", "微软雅黑", sans-serif;
      color:var(--text-main);
      overflow:hidden;
      touch-action: none;
    }
    body {
      display: flex;
      justify-content: center;
      align-items: center;
      min-height:100vh;
      width:100vw;
      background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><path d="M0,0 L100,100 M100,0 L0,100" stroke="%23ffd87b33" stroke-width="0.5"/></svg>');
    }
    #phone-frame {
      width: 375px;
      height: 725px;
      border-radius: 39px;
      box-shadow: 0 8px 32px 0 #40230436;
      background: #e2d3c1;
      border:8px solid #f3c893;
      position:relative;
      overflow: hidden;
      display:flex;
      flex-direction:column;
    }
    #screen {
      flex:1;
      width:100%;
      height:100%;
      overflow:hidden;
      background:var(--main-grad);
      padding:16px 0 8px 0;
      box-sizing:border-box;
      position: relative;
    }
    .card {
      background:var(--card-bg);
      border:var(--border);
      box-shadow: var(--shadow);
      border-radius:var(--border-radius);
      margin:7px 18px 19px 18px;
      padding:15px 17px 15px 17px;
      position:relative;
      min-height:42px;
      transition:box-shadow 0.3s;
      overflow:hidden;
    }
    .card-title {
      font-weight:bold;
      font-size:1.18em;
      letter-spacing:0.02em;
      margin-bottom:7px;
      color:#a56813;
      display:flex;align-items:center;gap:0.35em;
      text-shadow: 0 1px 2px rgba(0,0,0,0.1);
    }
    .info-card {
      background:var(--zone1-bg);
      border:2.5px double #eeaf27;
      color:#995700;
      font-size:0.93em;
      font-weight:bold;
    }
    .row {
      display:flex;align-items:center;
      gap:16px;
    }
    .player-card {
      display:flex;flex-direction:row;
      background:var(--card-bg);
      border:2.5px solid #eec378;
      min-height:92px;
      padding:0;
      box-shadow:0 2px 12px #ffb73d45;
      overflow:hidden;
    }
    .player-avatar-side{
      flex:0 0 38.2%;
      display:flex;justify-content:center;align-items:center;
      background: linear-gradient(135deg,#feebc5 60%,#ffc793 100%);
      border-right:2.5px solid #f2d399;
      height:100%;
      min-width: 0;
      position:relative;
    }
    .avatar-breathing {
      border-radius:50%;
      width:68px;height:68px;
      background-color:#fff6e6;
      border:3.5px solid #ffeab9;
      box-shadow:0 0 0 0 #ffeac5;
      overflow:hidden;
      animation:breath 2.3s infinite alternate;
      position:relative;
      z-index:2;
    }
    .avatar-img{width:68px;height:68px;object-fit:cover;border-radius:50%;}
    .avatar-upload-btn {
      border:1px solid #f2cea7;
      background:#fffbe8d7;
      font-size:0.86em;
      color:#aa7e13;
      border-radius:15px;
      cursor:pointer;
      margin-top:5px;
      padding:2px 7px;
      transition:background 0.2s;
      box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }
    .avatar-upload-btn:active{background:#ffe2b3;}
    @keyframes breath {
      0%{box-shadow:0 0 0 0 #ffeac5;}
      100%{box-shadow:0 0 22px 10px #ffe5b3b0;}
    }
    .player-status-side{
      flex:1;
      display:flex;
      flex-direction:column;
      justify-content:center;
      gap:4px;
      background: linear-gradient(95deg,#fff0d7 82%,#f6ebf7 100%);
      min-width:0;
      height:100%;
      padding:11px 0 11px 6px;
      position:relative;
    }
    .status-row{display:flex;align-items:center;gap:9px;font-size:1em;}
    .stat-label{color:#db9700;font-weight:bold;}
    .stat-bar-wrap{flex:1;margin:0 0 0 7px;}
    .stat-bar-bk{
      background:var(--bar-bg);
      border-radius:8px;overflow:hidden;
      height:13px;width:100%;position:relative;
      box-shadow:0 1.5px 7px #ffe7baa7, 0 0 6px #fff6d1c1 inset;
    }
    .stat-bar-fill{
      background: linear-gradient(90deg,#fff9bc 10%,#ffc369 48%,#ffe0b6 100%);
      height:100%;width:0;transition:width 0.56s cubic-bezier(.25,1.6,.57,1);
      border-radius:8px;
      box-shadow:var(--bar-glow);
      position:relative;
      overflow:hidden;
      animation:glowmove 1.5s infinite alternate;
    }
    @keyframes glowmove {
      50%{box-shadow:0 0 33px 13px #ffe5a7d0;}
      100%{box-shadow:0 0 10px 4px #ffd7b260;}
      0%{box-shadow:0 0 16px 4px #ffe4b0cc;}
    }
    /* 分区视觉增强 */
    .zone1{background: var(--zone1-bg);}
    .zone2{background: var(--zone2-bg);}
    .zone3{background: var(--zone3-bg);}
    .zone4{background: var(--zone4-bg);}
    .zone5{background: var(--zone5-bg);}
    .zone6{background: var(--zone6-bg);}

    .main-story-card{
      background:linear-gradient(100deg,#fffef6 60%,#fff6e7 100%);
      border:2.5px solid #fcda8b;
      box-shadow:0 8px 32px -4px #fad46d7c;
      border-radius:20px;
      color:#a8752b;
      font-size:1.09em;
      font-family:"霞鹜文楷","苹方","PingFang SC","微软雅黑",sans-serif;
      margin-bottom:14px;
      position: relative;
    }
    .story-img-wrap{width:98px;height:81px;float:right;margin:0 0 6px 10px;}
    .story-img{width:100%;height:100%;object-fit:cover;border-radius:9px;box-shadow:0 4px 14px #ffd77c67;border:2px solid #ffeaad;}
    .story-title{font-weight:bold;color:#ff9700;font-size:1.12em;margin-bottom:8px}
    .story-location{color:#cf890d;font-size:0.93em;}
    .story-sys{color:#7e6802;font-size:0.92em;font-weight:bold;margin-bottom:9px;margin-top:5px;}
    .story-txt{white-space:pre-line;line-height:1.38em;}
    .choices-list{display:flex;flex-direction:column;gap:12px;margin-top:14px;margin-bottom:8px;}
    .story-choice-btn{
      background:var(--accent-gradient);
      border:1.7px solid #ffbe71;
      border-radius:14px;
      box-shadow:0 2px 7px #fff1d558,0 0.5px 1.5px #ffa940;
      color:#ae5400;
      font-weight:bold;
      font-size:1.08em;
      padding:11px 13px;
      cursor:pointer;
      transition:background 0.17s, transform .13s;
      text-align: center;
    }
    .story-choice-btn:active{background:#fbe9da;transform:scale(0.94);}
    .option-unavailable{opacity:0.32;pointer-events:none;}

    .tool-btn-area{
      display:flex;
      flex-wrap:wrap;
      gap:13px 10px;
      justify-content:center;
      margin-top:9px;
    }
    .tool-btn{
      background:linear-gradient(86deg,#fff3de 75%,#ffe4c6 100%);
      border:1.5px solid #ecd5b6;
      border-radius:12px;
      color:#bc8407;
      box-shadow:0 1.5px 7px #fff7df2e;
      font-size:1.03em;
      font-weight:bold;
      padding:6.5px 17px;
      margin:3px 0;
      cursor:pointer;
      transition:background 0.2s;
      min-width: 120px;
    }
    .tool-btn:active{background:#fff6d1;}
    /* NPC卡片 */
    .npc-card{display:flex;align-items:center;gap:11px;padding:6px 8px;background-color:#fdddbb88;border-radius:15px;border:2px solid #ffd6c3;box-shadow:0 1px 8px #ffe0b5c0;margin-bottom:7px;position:relative;}
    .npc-avatar{width:44px;height:44px;border-radius:50%;border:2px solid #ffd887;object-fit:cover;background:#fff7e1;}
    .npc-info{flex:1;display:flex;flex-direction:column;gap:1.5px;}
    .npc-name{font-weight:bold;color:#a96711;}
    .npc-mood{font-size:0.96em;color:#937400;}
    .npc-bubble{
      position:absolute;
      right:0;
      top:4px;
      background:#fff9e7b8;
      border-radius:10px 13px 15px 14px;
      padding:5px 12px 6px 7px;
      font-size:0.95em;
      box-shadow:0 1px 5px #f8d04d29;
      border:1.5px solid #ffd796;
      color:#475600;
      min-width:56px;
      z-index:5;
    }
    /* 悬浮操作区 */
    #file-selector{
      display:none;position:absolute;z-index:99;
    }
    #music-selector{display:none;}
    .music-bar{display:flex;align-items:center;gap:7px;margin-top:5px;}
    .music-audio{width:185px;height:22px;vertical-align:middle;}
    .music-filename{font-size:0.97em;color:#be7812;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:92px;}
    /* 随机事件列表卡片*/
    .event-list{
      display:flex;
      flex-direction:column;
      gap:9px;
    }
    .mini-card{
      border:2px solid #ffe190;
      border-radius:13px;
      background:linear-gradient(91deg,#fffbe1 60%,#e8fced 100%);
      box-shadow:0 0.5px 6px #fff7de66;
      padding:7px 11px 5px 11px;
      font-size:0.99em;
    }
    .mini-title{font-weight:bold;color:#daad01;}
    .mini-txt{line-height:1.22em;color:#715108;}
    /* 成就卡片 */
    .achieve-list{display:flex;flex-wrap:wrap;gap:9px;}
    .achieve-item{
      border:2px solid #ffaed8;
      background:linear-gradient(93deg,#fff6ff 90%,#ffe9e3 100%);
      border-radius:13px;
      color:#ad08c6;
      box-shadow:0 0 10px #e2d6fc33;
      padding:4px 13px;
      font-size:1.04em;
    }
    /* "手机头部/底部" 装饰 */
    #header-bar{
      width:100%;height:28px;background:linear-gradient(90deg,#fff7d1,#eed3ad);display:flex;justify-content:center;align-items:center;font-weight:bold;letter-spacing:0.08em;font-size:1.16em;color:#ad7f1b;border-radius:18px 18px 0 0;box-shadow:0 2px 10px #f8edd780;
    }
    #footer-bar{
      width:100%;height:18px;background:linear-gradient(90deg,#ffeede,#fffde5 55%);border-radius:0 0 18px 18px;display:flex;justify-content:center;align-items:center;box-shadow:0 -2px 10px #faeac145;font-size:.93em;color:#be8b2e;font-weight:bold;
    }
    /* 滚动条 */
    #screen::-webkit-scrollbar {width:7px;background:#ffeab27c;}
    #screen::-webkit-scrollbar-thumb {background:#ffe9ba;border-radius:8px;}
    @media (max-width:400px) {
      #phone-frame{max-width:100vw!important;width:100vw;}
      #screen{padding:4.5vw 0;}
      .card,.player-card{margin-right:8px;margin-left:8px;}
    }
    /* 表情符号自定义 */
    .emj {font-size:1.2em;vertical-align:middle;}
    /* 动画按钮/区块 */
    .pulse-anim {animation: pulse2 1.38s infinite alternate;}
    @keyframes pulse2 { 0% {box-shadow:0 0 10px #ffeac7ff;} 100% {box-shadow:0 0 24px #ffecc3bb;} }
    
    /* 新增样式 */
    .copyright {
      font-size: 0.8em;
      text-align: center;
      color: #a56813;
      margin-top: 10px;
      padding: 5px;
      border-top: 1px dashed #eec378;
    }
    
    .task-item {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      padding: 5px;
      border-radius: 8px;
      background: rgba(255, 255, 255, 0.5);
    }
    
    .task-checkbox {
      margin-right: 10px;
    }
    
    .task-done {
      text-decoration: line-through;
      opacity: 0.7;
    }
    
    .family-member {
      padding: 5px 10px;
      background: rgba(255, 255, 255, 0.7);
      border-radius: 10px;
      margin: 3px;
      display: inline-block;
      border: 1px solid #f2d399;
    }
    
    .teahouse-rules {
      list-style-type: none;
      padding-left: 15px;
    }
    
    .teahouse-rules li {
      margin-bottom: 8px;
      position: relative;
      padding-left: 20px;
    }
    
    .teahouse-rules li:before {
      content: "⚜️";
      position: absolute;
      left: 0;
    }
    
    .cooking-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;
      padding: 5px;
      border-bottom: 1px dashed #eec378;
    }
    
    .dialog-bubble {
      background: #fff9e7;
      border-radius: 12px;
      padding: 8px 12px;
      margin: 5px 0;
      border: 1px solid #ffd796;
      box-shadow: 0 1px 3px rgba(0,0,0,0.1);
      position: relative;
    }
    
    .dialog-bubble:after {
      content: '';
      position: absolute;
      bottom: -10px;
      left: 20px;
      border-width: 10px 10px 0;
      border-style: solid;
      border-color: #fff9e7 transparent;
    }
    
    .bubble-system {
      background: #e8fced;
      border-color: #b3ebff;
    }
    
    .bubble-system:after {
      border-color: #e8fced transparent;
    }
    
    /* 新添加的样式 */
    .identity-option {
      border: 2px solid #feba78;
      border-radius: 15px;
      padding: 10px;
      margin-bottom: 10px;
      background: #fff6e7;
      cursor: pointer;
      transition: all 0.3s;
    }
    
    .identity-option:hover {
      background: #ffedc8;
      transform: translateY(-3px);
    }
    
    .identity-option.selected {
      background: #ffdfa3;
      box-shadow: 0 0 10px #ffd87b;
    }
    
    .cooking-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 10px;
    }
    
    .cooking-btn {
      padding: 10px;
      text-align: center;
      background: linear-gradient(90deg, #fff9bc, #ffc369);
      border-radius: 10px;
      border: 1px solid #f2d399;
      cursor: pointer;
    }
    
    .betting-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 5px;
      margin-top: 10px;
    }
    
    .betting-option {
      padding: 8px;
      text-align: center;
      background: linear-gradient(90deg, #fff9e7, #b3ebff);
      border-radius: 8px;
      border: 1px solid #f2d399;
      cursor: pointer;
    }
    
    .note-item {
      border: 1px solid #ffd796;
      border-radius: 10px;
      padding: 8px;
      margin-bottom: 8px;
      background: #fff9e7;
    }
    
    .task-board {
      border: 1px solid #eec378;
      border-radius: 10px;
      padding: 10px;
      background: #fff9e7;
      margin-bottom: 15px;
    }
    
    .task-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      padding-bottom: 5px;
      border-bottom: 1px dashed #eec378;
    }
    
    .task-progress {
      height: 10px;
      background: #f2d399;
      border-radius: 5px;
      margin: 5px 0;
    }
    
    .task-progress-fill {
      height: 100%;
      background: #ffc369;
      border-radius: 5px;
      width: 0%;
      transition: width 0.5s;
    }
    
    .npc-relation-bar {
      height: 5px;
      background: #f2d399;
      border-radius: 3px;
      margin: 3px 0;
    }
    
    .npc-relation-fill {
      height: 100%;
      background: #ff6b6b;
      border-radius: 3px;
    }
    
    .save-slot {
      border: 2px solid #eec378;
      border-radius: 10px;
      padding: 10px;
      margin-bottom: 10px;
      background: #fff9e7;
      cursor: pointer;
    }
    
    .save-slot:hover {
      background: #ffedc8;
    }
    
    .save-info {
      font-size: 0.9em;
      color: #a56813;
    }
    
    .recipe-card {
      border: 1px solid #ffd796;
      border-radius: 10px;
      padding: 10px;
      margin-bottom: 10px;
      background: #fff9e7;
    }
    
    .recipe-title {
      font-weight: bold;
      color: #ff9700;
      margin-bottom: 5px;
    }
    
    .fade-in {
      animation: fadeIn 0.6s ease-in;
    }
    
    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(20px); }
      to { opacity: 1; transform: translateY(0); }
    }
    
    .scene-container {
      height: 100%;
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }
    
    .scene-content {
      flex: 1;
      overflow-y: auto;
      overflow-x: hidden;
      position: relative;
    }
    
    .scene-animation {
      position: absolute;
      width: 100%;
      height: 100%;
      animation: fadeIn 0.8s ease-out;
    }
    
    .scene-nav {
      display: flex;
      justify-content: center;
      gap: 10px;
      padding: 10px;
      background: rgba(255, 248, 225, 0.9);
      border-top: 2px solid #ffd87b;
    }
    
    .nav-btn {
      padding: 8px 16px;
      border-radius: 20px;
      background: linear-gradient(90deg, #ffc369, #ffe0b6);
      border: 1px solid #eec378;
      font-weight: bold;
      color: #703704;
      cursor: pointer;
      box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    }
    
    .nav-btn:active {
      transform: scale(0.95);
    }
    
    /* 新增：滚动区域 */
    .scrollable-area {
      max-height: 300px;
      overflow-y: auto;
      padding-right: 5px;
    }
    
    /* 新增：加载动画 */
    .loading-spinner {
      display: inline-block;
      width: 20px;
      height: 20px;
      border: 3px solid rgba(255, 255, 255, 0.3);
      border-radius: 50%;
      border-top-color: #ffc369;
      animation: spin 1s ease-in-out infinite;
    }
    
    @keyframes spin {
      to { transform: rotate(360deg); }
    }
    
    /* 新增：确保文本不遮挡 */
    .text-safe {
      padding: 10px;
      line-height: 1.5;
    }
    
    /* 新增：成就佩戴按钮 */
    .equip-btn {
      background: linear-gradient(90deg, #ffd87b, #ffb564);
      border: 1px solid #eec378;
      border-radius: 8px;
      padding: 3px 8px;
      font-size: 0.8em;
      margin-left: 5px;
      cursor: pointer;
    }
    
    /* 新增：茶馆话题样式 */
    .teahouse-topic {
      padding: 8px;
      margin-bottom: 8px;
      background: #fff9e7;
      border-radius: 10px;
      border: 1px dashed #eec378;
    }
    
    /* 新增：鸡肋系统状态 */
    .jile-status {
      padding: 5px;
      margin-bottom: 5px;
      background: rgba(255, 255, 255, 0.7);
      border-radius: 8px;
      border-left: 3px solid #ff6b6b;
    }
  </style>
</head>
<body>
  <div id="phone-frame">
    <div id="header-bar">⚜️古代魂穿系统⚜️</div>
    <div id="screen"></div>
    <div id="footer-bar">☁️ 美味厨房AI文游 ☁️</div>
    <!-- 隐藏的头像/音频选择器 -->
    <input id="file-selector" type="file" accept="image/*">
    <input id="music-selector" type="file" accept="audio/*"/>
  </div>
<script>
/**
 * 全局游戏状态管理对象
 */
const gameState = {
  step: "welcome", // welcome, chooseAvatar, chooseMusic, identity, main, story, eventX, viewInfo, viewNPC, viewSystem, viewTeahouse, viewAchieve, viewCooking, //...
  turn: 0,
  player: {
    nickname: "社畜001号",
    avatar: "", // base64
    gender: "男",
    mood: 60,
    health: 72,
    luck: 33,
    qiYun: 83,
    energy: 65,
    tags: ["加班狗","社死体质"],
    achievements: [],
    titles: [],
    equippedTitle: null, // 当前佩戴的称号
    equippedAchievement: null, // 当前佩戴的成就
    identity: null,
    family: [],
    skills: [],
    items:[],
    diary: [],
    location: "狗剩县大街",
    weather: "晴转多云，有鸟屎掉落风险",
    time: "巳时三刻",
    date: "永安朝三年 五月初五",
    dynasty: "永安朝",
    jileStatus: [] // 鸡肋系统状态
  },
  currentStoryId: "001",
  musicFile: null,
  musicUrl: "",
  // 记录互动
  eventHistory:[],
  // 新增存档相关
  saveCount: 0,
  lastSaveTurn: 0,
  // 茶馆相关数据
  teahouseWall: [
    {msg:"隔壁王老头昨晚又梦游，差点掉进粪坑！", ts:Date.now()-1000000},
    {msg:"谁偷了我的破碗？出来挨打！", ts:Date.now()-800000},
    {msg:"包子摊老板其实是个诗人，写的诗比包子还硬。", ts:Date.now()-600000}
  ],
  teahouseTopics: [
    "听说县令夫人昨晚在城墙上唱情歌，对象居然是月亮？",
    "捕快二狗今天又被老婆罚跪搓衣板，原因竟是没买糖葫芦",
    "神秘乞丐的宝藏地图到底藏在哪？有人知道吗？",
    "酸秀才写的新小说《霸道县令爱上我》在青楼热卖中",
    "今日最佳话题：如何用树叶擦屁股最舒服？"
  ],
  teahouseBet: {open:false, bets:[], result:null},
  teahouseNotes: [],
  // 任务系统
  tasks: [
    {name:"学习古代用筷子吃饭",desc:"别再用手抓饭，被店小二围观吐槽",done:false, progress:0, maxProgress:3},
    {name:"今日社死：大街上跳剑舞",desc:"虽然你不会剑舞，但跳完奖励50气运值",done:false, progress:0, maxProgress:1},
    {name:"完成新手懵逼期任务",desc:"学会用筷子夹菜，别把马桶当水桶",done:false, progress:0, maxProgress:5}
  ],
  // NPC八卦
  npcGossip: [
    "包子壮汉其实害怕小狗，小时候被咬过。",
    "书生张三背地里练广场舞，三更半夜常被抓包。",
    "老王原本是看门狗，因偷吃了县令的馒头被贬流浪。",
    "翠花姐暗恋隔壁摊大叔，每晚都赠送两串糖葫芦。",
    "捕快二狗最怕老婆，每次出任务先回家请示。",
    "酸秀才偷偷写现代言情小说，被青楼姑娘们追捧。",
    "县令夫人其实是武林高手，县令每天跪搓衣板。",
    "卖豆腐的寡妇每晚在城墙上唱情歌，对象是月亮。",
    "神秘乞丐其实是前朝首富，破产后装疯卖傻。",
    "店小二能用算盘玩出DJ效果，但老板不知道。"
  ],
  // 烹饪系统
  cookingItems: [
    {name:"萝卜", qty:3},
    {name:"白菜", qty:2},
    {name:"狗剩县馒头", qty:5},
    {name:"猪肉", qty:1},
    {name:"鸡蛋", qty:2},
    {name:"大米", qty:1}
  ],
  recipes: [
    {name:"晕头粥", ingredients:["大米"], desc:"喝了会头晕的粥，但能填饱肚子"},
    {name:"咸菜伴饭", ingredients:["大米", "白菜"], desc:"米饭配咸菜，古代社畜必备"},
    {name:"黑暗煎饼", ingredients:["鸡蛋", "面粉"], desc:"黑乎乎的煎饼，吃了可能拉肚子"},
    {name:"炖猪肉", ingredients:["猪肉", "萝卜"], desc:"香喷喷的炖肉，恢复体力"},
    {name:"炒白菜", ingredients:["白菜"], desc:"简单的炒菜，味道一般"}
  ],
  // 存档系统
  saveSlots: []
};

/** 表情化心情映射 */
function moodMap(val){
  if(val>88) return "💖 牛气冲天！";
  if(val>77) return "😄 元气满满";
  if(val>55) return "😊 还凑合";
  if(val>45) return "😌 累并快乐";
  if(val>33) return "🥲 一言难尽";
  if(val>20) return "😵 装作开心";
  return "😭 彻底emo";
}
function healthMap(v){
  if(v>80) return "💪 体力充沛";
  if(v>60) return "😌 小病小痛";
  if(v>33) return "🤧 感觉不妙";
  return "😱 半只脚进棺材";
}
function luckMap(v){
  if(v>70) return "🍀 欧皇降临";
  if(v>40) return "🫠 摇摆不定";
  return "💩 非酋附体";
}
function getTitle(){
  // 展示已获得称号
  return (gameState.player.equippedTitle) 
    ? '👑 ' + gameState.player.equippedTitle
    : '平平无奇小社畜'
}
function getPlayerSkillDesc(){
  // 技能搞笑描述
  if(gameState.player.skills.length==0) return "呼吸吐纳（LV1，系统：谁不会喘气啊…）";
  return gameState.player.skills.map(sk=>sk.name+"("+sk.lv+")："+sk.desc).join('、');
}
/** 头像处理 */
function handleAvatarUpload(file){
  const reader = new FileReader();
  reader.onload = function(e){
    gameState.player.avatar = e.target.result;
    render();
  }
  reader.readAsDataURL(file);
}
/** 音乐处理 */
function handleMusicUpload(file){
  const reader = new FileReader();
  reader.onload = function(e){
    gameState.musicUrl = e.target.result;
    render();
  }
  reader.readAsDataURL(file);
}

// 随机初始身份池
const identityPool = [
  {name:"狗剩县乞丐", origin:"内卷猝死社畜",
    desc:"你本是狗剩县举世无双的咸鱼专业户，一觉醒来却发现自己只剩破碗一只。曾因抢馒头大战被评为'地表最强流浪者'。",skills:[{name:"讨饭大法", lv:1, desc:"开口就是金句，收获残羹剩饭。"}]},
  {name:"翠花郡丫鬟",origin:"周末躺平少女",
    desc:"上辈子风风火火加班命，这辈子咖啡换茶水，老板换姨娘，技能还是'说一句，做一半'。",skills:[{name:"躺平术",lv:1,desc:"见事不对，立刻装晕。"}]},
  {name:"秀才镇穷书生",origin:"摸鱼打工人",
    desc:"穿越之路一波三折，自称'隔壁最能熬夜的背书机器'。本地文人争相膜拜你的百度经验。",skills:[{name:"瞎编诗",lv:1,desc:"以现代名言迷惑评委。"}]},
  {name:"镖局厨子",origin:"菜市场小老板",
    desc:"你能把土豆丝炒成代码，更能把锅碗瓢盆敲成摇滚；镖师们吃你的饭，嘴上笑背后骂。",skills:[{name:"炊事内卷",lv:1,desc:"能炒一口气，能卷一屋菜。"}]},
  {name:"捕快二狗",origin:"996保安队长",
    desc:"一夜醒来铁饭碗变铁链子，从小区巡逻穿越到抓贼，嘴上三句话：'站住'、'交出你的鸡腿'、'你完了'。",skills:[{name:"破案甩锅",lv:1,desc:"什么都归前任，啥都能推锅。"}]},
  {name:"青楼抓猫人",origin:"宠物店店员",
    desc:"专业抓捕逃跑的猫咪，但在青楼抓猫时经常被误会成登徒子，脸上常带抓痕。",skills:[{name:"猫语十级",lv:1,desc:"能听懂猫叫，但猫不理你。"}]},
  {name:"皇家铲屎官",origin:"动物园饲养员",
    desc:"负责清理皇家动物园，整天与各种动物粪便打交道，身上总有一股特别的味道。",skills:[{name:"铲屎大法",lv:1,desc:"清理粪便速度提升200%。"}]},
  {name:"城门看门狗训导员",origin:"训犬师",
    desc:"负责训练城门看门犬，但狗们只听骨头的话，不听你的话。",skills:[{name:"骨头诱惑",lv:1,desc:"用骨头让狗暂时听话。"}]},
  {name:"衙门试菜员",origin:"美食评论家",
    desc:"每天试吃县令的黑暗料理，练就了金刚不坏的胃和味觉失灵的本领。",skills:[{name:"铁胃",lv:1,desc:"能吃下任何不明物体。"}]}
];

// 鸡肋系统搞笑事件
const sysJilegEvents = [
  "今日气运：非酋附体——走路必踩狗屎!",
  "鸡肋技能：徒手揪蚊，落空率99%。",
  "系统恶搞：睡觉打鼾如雷，邻居搬家。",
  "坑爹任务：必须用粤语操场跑三圈，否则罚吃冷包子。",
  "今日整蛊：穿鞋左右不分，鞋带互绑！",
  "额外祝福：嘴角流油，不自知。",
  "限定debuff：下雨天必带伞，但伞必破。",
  "乌鸦嘴生效：你说'今天应该不会下雨吧'，结果暴雨倾盆。",
  "蝴蝶效应：你不小心踩死蚂蚁，导致蚂蚁家族全体复仇。",
  "系统抽风：你的头发突然变成彩虹色，持续一炷香时间。",
  "今日增益：说话自带回音，吓跑路人",
  "奇葩事件：被一只鸡追了三条街，原因是你穿了红色裤子",
  "系统赠送：一块会发光的石头（其实是萤火虫）",
  "倒霉事件：出门被鸟屎砸中，获得'天降祥瑞'称号",
  "搞笑任务：教县令家的狗背三字经"
];

// 剧情流程库
const storyData = {
  "001": {
    id:"001",
    title:"重生魂穿大奇葩！",
    image:"",
    location:"狗剩县大街",
    sys:"【系统提示】你社畜加班猝死，非酋附体，转生为破碗一只的古代乞丐。人生巅峰，真的地上躺！",
    text:
      '一睁眼，你发现全身脏兮兮，身边围着三只流浪狗，一只比你还瘦。\n\n“啪嗒一下”，鼻尖落了坨鸟屎——不愧是你，上辈子996遭老板压榨，这辈子连鸟都要欺负你。\n\n' +
      '【系统吐槽】：\n“穿越必踩狗屎，重生自带社死体。”\n\n' +
      '附近有：\n' +
      '1. 街角卖包子的壮汉正用奇怪眼神看你。',
    options: [
      {
        text:"a. 对着狗作揖，混个脸熟",
        nextStoryId:"002a",
        effects:{mood: +5, health:-2, luck:-8},
      },
      {
        text:"b. 抢隔壁乞丐破碗当乐器",
        nextStoryId:"002b",
        effects:{luck:+7, mood:-3, qiYun:-6},
      },
      {
        text:"c. 用现代绕口令挑战书生",
        nextStoryId:"002c",
        effects:{mood:+2, health:-3, qiYun:+4},
      },
      {
        text:"d. 假装晕倒，暗中偷瞄包子",
        nextStoryId:"002d",
        effects:{mood:+1, health:-1, luck:+7},
      },
      {
        text:"e. 把系统吐槽当耳边风",
        nextStoryId:"002e",
        effects:{qiYun:+3, mood:-2},
      },
    ]
  },
  "002a":{ //下一幕，狗互动
    id:"002a",
    title:"狗狗也懂江湖道",
    image:"",
    location:"狗剩县大街",
    sys:"你深深鞠了一躬，三只狗互相看看：‘兄弟，这新来的，不简单。’\n‘汪！汪汪！’（大意：有点东西…）",
    text:"结果一只狗把你当成兄弟，趴你旁边求抱抱。\n系统感叹：‘社畜灵魂，狗生共鸣。’\n你收获：流浪狗友谊+1，路人的同情-1。\n\n【电视剧治愈bgm响起】\n\n刚刚那个包子壮汉大喊：‘喂！新来的想吃饭先拜码头！’\n你还来不及回神，身旁的狗摇了摇脑袋，似乎劝你‘别傻，骨头都给他嚼过’。\n\n这画风突变，难道真要选小狗做大哥？\n【你怀疑自己要不要拜投狗帮】",
    options:[
      {
        text:"a. 马上跟狗结拜——舔骨头仪式",
        nextStoryId:"003a",
        effects:{mood:+5, luck:-5}
      },
      {
        text:"b. 利用狗吸引包子壮汉注意",
        nextStoryId:"003b",effects:{luck:+3, health:-2}
      },
      {
        text:"c. 捡地上菜叶假装有吃的",
        nextStoryId:"003c",effects:{health:+2, mood:-1}
      },
      {
        text:"d. 静观其变，装傻充呆",
        nextStoryId:"003d",effects:{luck:+2, mood:+1}
      },
      {
        text:"e. 假装失忆，胡言乱语求饶",
        nextStoryId:"003e",effects:{mood:-2, luck:+4}
      },
    ]
  },
  "002b": {
    id:"002b",
    title:"丐帮音乐家",
    image:"",
    location:"狗剩县大街",
    sys:"你一把抢过隔壁老乞丐的破碗，用树枝敲打起来！",
    text:"叮叮当当~ 你敲出了一段现代DJ节奏，引来路人围观。\n老乞丐怒目圆睁：‘小子，那是老夫的饭碗！’\n\n围观群众议论纷纷：‘这新来的乞丐有才啊！’\n‘敲得比城西戏班子还带劲！’\n\n包子壮汉也探头看热闹，你该如何应对？",
    options:[
      {
        text:"a. 继续敲打，表演更嗨的节奏",
        nextStoryId:"003f",
        effects:{mood:+8, luck:-3}
      },
      {
        text:"b. 把碗还给老乞丐，鞠躬道歉",
        nextStoryId:"003g",
        effects:{luck:+4, mood:+1}
      },
      {
        text:"c. 邀请老乞丐一起演奏",
        nextStoryId:"003h",
        effects:{qiYun:+5, mood:+2}
      },
      {
        text:"d. 用碗向路人讨赏",
        nextStoryId:"003i",
        effects:{mood:+3, luck:+2}
      },
    ]
  },
  "002c": {
    id:"002c",
    title:"绕口令大战",
    image:"",
    location:"狗剩县大街",
    sys:"你走到书生面前：‘八百标兵奔北坡！’",
    text:"书生一脸懵：‘兄台何意？’\n你继续：‘炮兵并排北边跑！’\n书生脸色发青：‘这...这是何妖术？’\n\n围观群众越来越多，连包子壮汉也凑了过来。",
    options:[
      {
        text:"a. 继续念：‘炮兵怕把标兵碰！’",
        nextStoryId:"003j",
        effects:{qiYun:+7, mood:+3}
      },
      {
        text:"b. 解释这是现代绕口令",
        nextStoryId:"003k",
        effects:{luck:+2, mood:-1}
      },
      {
        text:"c. 挑战书生对诗",
        nextStoryId:"003l",
        effects:{qiYun:+5, luck:-2}
      },
      {
        text:"d. 假装被附体，胡言乱语",
        nextStoryId:"003m",
        effects:{mood:+1, luck:+3}
      },
    ]
  },
  "002d": {
    id:"002d",
    title:"影帝诞生",
    image:"",
    location:"狗剩县大街",
    sys:"你突然倒地抽搐，口吐白沫！",
    text:"‘哎呀！新来的晕倒了！’路人惊呼。\n包子壮汉皱眉：‘别装死，老子见多了！’\n\n你眯着眼偷看，包子热气腾腾，香气扑鼻...\n肚子咕咕叫得更响了！",
    options:[
      {
        text:"a. 继续装晕，等待救援",
        nextStoryId:"003n",
        effects:{health:-3, luck:+5}
      },
      {
        text:"b. 突然跳起抢包子",
        nextStoryId:"003o",
        effects:{health:+5, mood:-2}
      },
      {
        text:"c. 声称自己失忆了",
        nextStoryId:"003p",
        effects:{mood:+2, qiYun:+3}
      },
      {
        text:"d. 抱住壮汉大腿求包子",
        nextStoryId:"003q",
        effects:{mood:+3, luck:+2}
      },
    ]
  },
  "002e": {
    id:"002e",
    title:"佛系穿越者",
    image:"",
    location:"狗剩县大街",
    sys:"你无视系统吐槽，淡定掏耳朵",
    text:"系统：‘喂！你听见没有？’\n你：‘听见了，但不想理你。’\n\n三只流浪狗围着你转圈，包子壮汉盯着你看，书生摇头晃脑走来...\n你该如何在这混乱中生存？",
    options:[
      {
        text:"a. 继续淡定，观察环境",
        nextStoryId:"003r",
        effects:{qiYun:+4, mood:+1}
      },
      {
        text:"b. 主动向包子壮汉打招呼",
        nextStoryId:"003s",
        effects:{luck:+3, mood:+2}
      },
      {
        text:"c. 跟流浪狗聊天",
        nextStoryId:"003t",
        effects:{mood:+5, health:-1}
      },
      {
        text:"d. 找书生请教古文",
        nextStoryId:"003u",
        effects:{qiYun:+6, mood:-1}
      },
    ]
  },
  "003a": {
    id:"003a",
    title:"狗剩县地下势力",
    location:"狗剩县后街阴影下",
    sys:"【系统】：没想到吧，你正式拜狗为大哥，这画风越来越迷了。",
    text:
      "你虔诚地捧着半根骨头，三只流浪狗围成一圈，你学电视剧那样搭手，狗却开始互相舔尾巴——大哥仪式搅成毛球乱战。\n\n"+
      "一旁小孩路过：‘娘你快看，有个傻子和狗拜堂！’旁边围观的阿婆乐到直拍大腿。\n\n"+
      "就在此时，真正的狗剩县地头狗‘老王’现身。他戴着红花领巾，甩出一个造型：‘以后一起分骨头！要混就混最底层！’\n\n"+
      "系统疯狂刷弹幕：【恭喜主控获得成就——‘狗生赢家’】\n\n"+
      "全场爆笑中，你从此获得了狗剩县真正的庇护…只不过大家以后见你都要喂一块骨头。\n",
    options:[
      {text:"a. 宣布成立骨头分配委员会", nextStoryId:"004a", effects:{luck:+3, mood:+4}},
      {text:"b. 和地头狗‘老王’合影发朋友圈（？）", nextStoryId:"004b", effects:{mood:+6, health:-1}},
      {text:"c. 狗狗围坐直播卖艺", nextStoryId:"004c", effects:{qiYun:+8, mood:+1}},
      {text:"d. 带着狗一起讨饭，打造乞丐天团", nextStoryId:"004d", effects:{luck:+7}},
      {text:"e. 忽然羞耻，装病逃离现场", nextStoryId:"004e", effects:{mood:-3, qiYun:+1}},
    ]
  },
  "003b":{
    id:"003b",
    title:"包子壮汉惊呆了",
    location:"狗剩县广场",
    sys:"壮汉：‘咦？这小子带狗来抢饭？胆肥！’",
    text:"你指挥流浪狗‘冲锋’，狗群蜂拥围在包子摊下，一边‘汪’，一边撒娇。\n壮汉见势不妙，只能赏了两根毫无味道的烧麦皮——你抢到‘狗粮’新资源全靠狗功劳。\n\n"+
      "【系统提示】获得狗剩县‘狗奴’称号！\n包子壮汉表情逐渐阴郁：‘臭小子，下次再见，狗都带不活你。’\n",
    options:[
      {text:"a. 顺势蹲下啃烧麦皮", nextStoryId:"005a", effects:{health:+3, mood:-2}},
      {text:"b. 让狗抢包子再分割", nextStoryId:"005b", effects:{luck:+6, qiYun:-3}},
      {text:"c. 装成卖艺丐帮求包子", nextStoryId:"005c", effects:{mood:+4, health:-4}},
      {text:"d. 当场拉狗'坐地起哄'", nextStoryId:"005d", effects:{luck:+3, mood:+1}},
      {text:"e. 向旁边路人求助", nextStoryId:"005e", effects:{mood:+2, luck:+1}},
    ]
  },
  "004a": {
    id:"004a",
    title:"正儿八经分骨头",
    location:"狗剩县桥洞下",
    sys:"你摇头晃脑宣布‘狗剩县骨头分配委员会’成立，但三只狗只顾啃骨头，不鸟你。",
    text:"你举着半根骨头当权杖，大肆演讲：‘公平公正公开，骨头人人有份！’\n"+
    "但台下观众（包括狗）全沉迷于肚皮抖动和麻花尾巴，无人鼓掌。突然，一只狗起身撒尿表示支持，你顿时社死度飙升。\n\n"+
    "【系统吐槽】：主角果然有管理才能……只是对象物种不太对。\n大伙一哄而散，咸鱼社畜找到了归属（不过是四只脚的）。\n",
    options:[
      {text:"a. 狗狗'民主投票'分蛋壳", nextStoryId:"006a", effects:{luck:+2, mood:+3}},
      {text:"b. 骨头立遗嘱给下一只狗", nextStoryId:"006b", effects:{luck:-1, health:+5}},
      {text:"c. 卸任委员会主席跑路", nextStoryId:"006c", effects:{mood:-2, qiYun:+8}},
      {text:"d. 拉横幅举办骨头歌会", nextStoryId:"006d", effects:{mood:+6, luck:+2}},
      {text:"e. 继续管理，强行分饼", nextStoryId:"006e", effects:{luck:+6, mood:-2}},
    ]
  },
  "005a": {
    id:"005a",
    title:"烧麦皮的滋味",
    location:"包子铺门口",
    sys:"【系统】：烧麦皮没味道？不，这是生活的味道！",
    text:"你蹲在路边啃着毫无味道的烧麦皮，三只狗围着你流口水。\n包子壮汉看到这一幕，居然有点感动：‘这小子，真不挑食啊！’\n\n"+
    "突然，壮汉扔来一个肉包子：‘赏你的！教教你家狗别总盯着我摊子！’\n\n"+
    "你接住包子，热泪盈眶——穿越以来第一顿正经饭！\n【系统提示】：获得‘不挑食的好孩子’成就！",
    options:[
      {text:"a. 把肉包子分给狗兄弟们", nextStoryId:"007a", effects:{health:+10, mood:+5}},
      {text:"b. 自己狼吞虎咽吃掉包子", nextStoryId:"007b", effects:{health:+15, mood:-3}},
      {text:"c. 用包子引诱更多流浪狗", nextStoryId:"007c", effects:{qiYun:+5, luck:+3}},
      {text:"d. 向壮汉鞠躬感谢，求工作", nextStoryId:"007d", effects:{mood:+8, qiYun:+2}},
      {text:"e. 把包子当传家宝供起来", nextStoryId:"007e", effects:{luck:-5, mood:+1}},
    ]
  },
  "006a": {
    id:"006a",
    title:"狗界民主",
    location:"桥洞议事厅",
    sys:"三只狗盯着你手中的蛋壳，若有所思",
    text:"你：‘现在开始投票！同意吃蛋壳的汪一声，反对的汪两声！’\n三只狗：‘汪！’\n你：‘好！全票通过！’\n\n老王狗突然叼来一块肉：‘兄弟，别玩蛋壳了，跟我混有肉吃！’\n\n原来老王狗发现了一个神秘食物源...",
    options:[
      {text:"a. 接受老王的邀请", nextStoryId:"008a", effects:{health:+10, mood:+5}},
      {text:"b. 坚持狗界民主原则", nextStoryId:"008b", effects:{qiYun:+5, mood:+3}},
      {text:"c. 带狗群去包子摊示威", nextStoryId:"008c", effects:{luck:+5, health:-2}},
      {text:"d. 研究蛋壳的108种吃法", nextStoryId:"008d", effects:{mood:+4, luck:-3}},
    ]
  },
  "007a": {
    id:"007a",
    title:"义薄云天",
    location:"包子铺墙角",
    sys:"你将肉包子分成四份，三份给狗",
    text:"三只狗狼吞虎咽，尾巴摇成螺旋桨！\n包子壮汉看在眼里：‘没想到你小子还挺讲义气！’\n\n壮汉走过来：‘以后每天来帮我赶苍蝇，管你一顿饭！’\n\n你终于找到了穿越后第一份工作——专业赶苍蝇！",
    options:[
      {text:"a. 感激接受工作", nextStoryId:"009a", effects:{mood:+10, health:+5}},
      {text:"b. 要求工资待遇", nextStoryId:"009b", effects:{luck:+5, mood:-2}},
      {text:"c. 让狗兄弟一起入职", nextStoryId:"009c", effects:{qiYun:+8, mood:+3}},
      {text:"d. 假装考虑三天", nextStoryId:"009d", effects:{luck:-3, mood:+1}},
    ]
  },
  "008a": {
    id:"008a",
    title:"神秘肉源",
    location:"县衙后巷",
    sys:"老王带你来到县衙后门垃圾桶",
    text:"老王：‘汪汪！’（翻译：县令家的剩菜！）\n你看着油腻的剩菜，陷入沉思...\n\n突然，后门打开，厨娘倒出一桶新剩菜！\n‘哟，新来的？挺会找地方啊！’厨娘笑道。",
    options:[
      {text:"a. 讨好厨娘求剩菜", nextStoryId:"010a", effects:{health:+10, mood:+3}},
      {text:"b. 假装美食家点评剩菜", nextStoryId:"010b", effects:{qiYun:+5, mood:+5}},
      {text:"c. 带狗群表演求打赏", nextStoryId:"010c", effects:{luck:+7, health:-2}},
      {text:"d. 开发剩菜新吃法", nextStoryId:"010d", effects:{mood:+4, luck:+3}},
    ]
  },
  "009a": {
    id:"009a",
    title:"职业赶蝇人",
    location:"包子铺",
    sys:"你获得新武器：苍蝇拍！",
    text:"‘啪！啪！啪！’\n你以专业手法击落三只苍蝇！\n包子壮汉：‘好手法！以前练过？’\n\n你：‘前世在互联网公司，天天和Bug打交道...’\n壮汉：‘？？？’",
    options:[
      {text:"a. 讲解互联网知识", nextStoryId:"011a", effects:{qiYun:+5, mood:+2}},
      {text:"b. 专注赶苍蝇事业", nextStoryId:"011b", effects:{health:+5, luck:+3}},
      {text:"c. 开发新式赶蝇法", nextStoryId:"011c", effects:{mood:+6, qiYun:+4}},
      {text:"d. 教狗兄弟赶苍蝇", nextStoryId:"011d", effects:{luck:+5, mood:+3}},
    ]
  },
  "010a": {
    id:"010a",
    title:"厨娘的红烧肉",
    location:"县衙后门",
    sys:"厨娘被你的马屁拍得心花怒放",
    text:"‘小嘴真甜！这碗红烧肉赏你了！’\n你接过还温热的红烧肉，泪流满面...\n\n老王狗急得直转圈：‘汪汪！’（翻译：分我点！）\n\n突然，县衙大门打开，县令大人走了出来！",
    options:[
      {text:"a. 躲进垃圾桶", nextStoryId:"012a", effects:{luck:+5, mood:-2}},
      {text:"b. 献上红烧肉", nextStoryId:"012b", effects:{qiYun:+10, health:+5}},
      {text:"c. 假装送外卖的", nextStoryId:"012c", effects:{mood:+4, luck:+3}},
      {text:"d. 教县令大人垃圾分类", nextStoryId:"012d", effects:{mood:+3, health:-3}},
    ]
  }
};

// NPC列表
const npcList = [
  {
    id:1,
    name:"包子壮汉",
    mood: 67,
    relation:15,
    emoji:"🧑‍🍳",
    avatar:"",
    bubble:"看什么看，想吃包子交保护费！",
    desc:"卖包子的壮汉，嗓门大如钟，一言不合就抄起扁担打人，暗恋翠花姐。",
    skills:["讨价还价LV5","吼叫攻击LV7"],
    location:"狗剩县东市"
  },
  {
    id:2,
    name:"书生张三",
    mood:49,
    relation:2,
    emoji:"📖",
    avatar:"",
    bubble:"你丑得像我的诗…",
    desc:"酸腐书生，满口之乎者也，实则连平仄都不懂，背地里练广场舞。",
    skills:["作诗LV3","掉书袋LV8"],
    location:"秀才镇私塾"
  },
  {
    id:3,
    name:"地头狗老王",
    mood:81,
    relation:22,
    emoji:"🐕",
    avatar:"",
    bubble:"汪！兄弟一起嗦骨头！",
    desc:"狗剩县地头狗，戴着红花领巾，统领三只流浪狗，曾是看门狗因偷吃被贬。",
    skills:["摇尾巴LV10","啃骨头LV9"],
    location:"狗剩县大街"
  },
  {
    id:4,
    name:"酸秀才李四",
    mood:55,
    relation:10,
    emoji:"🎓",
    avatar:"",
    bubble:"之乎者也，汝甚骚！",
    desc:"更酸的秀才，偷偷写现代言情小说，被青楼姑娘们追捧。",
    skills:["写小说LV6","酸倒牙LV9"],
    location:"秀才镇茶馆"
  },
  {
    id:5,
    name:"泼辣寡妇",
    mood:72,
    relation:5,
    emoji:"👩",
    avatar:"",
    bubble:"买豆腐不？不买别挡道！",
    desc:"卖豆腐的寡妇，嗓门大如钟，每晚在城墙上唱情歌，对象是月亮。",
    skills:["吆喝LV8","扁担攻击LV7"],
    location:"翠花郡西街"
  },
  {
    id:6,
    name:"奸商王老板",
    mood:88,
    relation:-10,
    emoji:"💰",
    avatar:"",
    bubble:"这个破碗值三文，爱当不当！",
    desc:"开当铺的奸商，专门坑蒙拐骗，收玩家的破碗当'古董'，给极低的价钱。",
    skills:["坑蒙拐骗LV9","假笑LV7"],
    location:"狗剩县当铺"
  },
  {
    id:7,
    name:"搞笑捕快",
    mood:60,
    relation:8,
    emoji:"👮",
    avatar:"",
    bubble:"再笑！再笑抓你去衙门！",
    desc:"表面严肃，实则喜欢听相声，最怕老婆，每次出任务先回家请示。",
    skills:["抓贼LV6","假正经LV8"],
    location:"衙门"
  },
  {
    id:8,
    name:"自恋少爷",
    mood:90,
    relation:0,
    emoji:"🎩",
    avatar:"",
    bubble:"本公子帅得惨绝人寰吧？",
    desc:"富二代，颜值低却自认潘安，到处撩妹，常被拒绝后闹笑话。",
    skills:["自恋LV10","撩妹LV3"],
    location:"翠花郡豪宅"
  },
  {
    id:9,
    name:"话痨厨子",
    mood:75,
    relation:12,
    emoji:"👨‍🍳",
    avatar:"",
    bubble:"你知道这白菜前世是啥吗？",
    desc:"在客栈做饭，边炒菜边唠叨，能把食材的前世今生都讲一遍。",
    skills:["唠叨LV9","炒菜LV7"],
    location:"悦来客栈"
  },
  {
    id:10,
    name:"神秘乞丐",
    mood:40,
    relation:25,
    emoji:"🧙",
    avatar:"",
    bubble:"少年，我看你骨骼惊奇...",
    desc:"脏兮兮的乞丐，据说曾是前朝首富，破产后装疯卖傻，可能藏有宝藏秘密。",
    skills:["装疯卖傻LV8","讲故事LV7"],
    location:"狗剩县桥洞"
  }
];

// 成就称号库
const achievementPool = [
  "狗生赢家", "社死体质王", "狗奴", "骨头分配官", "丐帮新秀", 
  "表情包大师", "踩狗屎专家", "鸟屎收集者", "非酋之光", "欧皇附体",
  "不挑食的好孩子", "狗语十级", "骨头鉴赏家", "街舞达人", "包子征服者",
  "乞丐皇帝", "搞笑之王", "鸡肋大师", "社死鼻祖", "生存专家"
];

// 家族成员库
const familyPool = [
  "你爹：张铁蛋（60岁，农民）", 
  "你娘：李翠花（58岁，爱唠叨）", 
  "二表哥：王麻子（35岁，赌鬼）", 
  "表姑：赵灵芝（50岁，媒婆）", 
  "三舅：李二狗（45岁，酒鬼）", 
  "表妹：翠花（18岁，恨嫁）", 
  "远房表叔：王老五（55岁，光棍）", 
  "姑婆：张寡妇（70岁，爱八卦）",
  "爷爷：张老汉（80岁，耳背）",
  "奶奶：李老太（78岁，爱抽旱烟）"
];

// 物品库
const itemPool = [
  {name:"破铜钱",desc:"几乎看不清字的古币",use:true,useResult:"你向包子摊花出去，被老板嫌弃收下！"},
  {name:"莫名其妙的葱花",desc:"总有人丢的东西",use:false},
  {name:"黑暗包子",desc:"闻着已长蘑菇，不敢吃",use:false},
  {name:"半只骨头",desc:"与狗共用",use:true,useResult:"狗看到你霸气分骨，集体尊你为兄！"},
  {name:"绳子",desc:"用途总会有的",use:false},
  {name:"神秘小纸条",desc:"写着'今夜有雨，速归'",use:true,useResult:"你假装神秘人士，吓跑路人一条街"},
  {name:"假牙",desc:"当铺老板丢失的",use:true,useResult:"还给当铺老板，获得10文钱"},
  {name:"会发光的石头",desc:"其实是萤火虫",use:true,useResult:"晚上当灯笼用，引来更多虫子"},
  {name:"绣着龙纹的内裤",desc:"谁这么大胆？",use:false},
  {name:"后悔药",desc:"吃了忘记自己后悔什么",use:true,useResult:"你忘记为什么吃这药了"}
];

// 鸡肋系统搞笑输出
function renderSysJile(forceThree){
  //三个
  let arr = [];
  while(arr.length<3){
    let s = sysJilegEvents[Math.floor(Math.random()*sysJilegEvents.length)];
    if(arr.indexOf(s)<0) arr.push(s);
  }
  return arr.map(s=>"<div class='jile-status'>🍗 "+s+"</div>").join("");
}

// 生成随机家族成员
function generateFamily() {
  if (gameState.player.family.length === 0) {
    // 随机生成1~4位家人
    let familyNum = Math.floor(Math.random()*4+1);
    gameState.player.family = [];
    for (let i = 0; i < familyNum; i++) {
      const randomIndex = Math.floor(Math.random() * familyPool.length);
      gameState.player.family.push(familyPool[randomIndex]);
    }
  }
}

// 添加成就
function addAchievement(achievement) {
  if (!gameState.player.achievements.includes(achievement)) {
    gameState.player.achievements.push(achievement);
    addDiary("获得成就：" + achievement);
    
    // 自动佩戴第一个成就
    if (!gameState.player.equippedAchievement) {
      gameState.player.equippedAchievement = achievement;
    }
  }
}

// 添加称号
function addTitle(title) {
  if (!gameState.player.titles.includes(title)) {
    gameState.player.titles.push(title);
    addDiary("获得称号：" + title);
    
    // 自动佩戴第一个称号
    if (!gameState.player.equippedTitle) {
      gameState.player.equippedTitle = title;
    }
  }
}

// 添加日记
function addDiary(msg) {
  if (!gameState.player.diary) gameState.player.diary = [];
  gameState.player.diary.unshift({
    ts: new Date().toLocaleString(),
    text: msg
  });
  if (gameState.player.diary.length > 10) gameState.player.diary.length = 10;
}

// 添加背包物品
function addBagItem(obj) {
  if (!gameState.player.items) gameState.player.items = [];
  if (typeof obj === "string") obj = {name: obj};
  gameState.player.items.push(obj);
  addDiary("获得道具：" + (obj.name || obj));
}

// 使用背包物品
function useBagItem(idx) {
  let obj = gameState.player.items[idx];
  addDiary("使用了物品：" + (obj.name || obj));
  let result = obj.useResult || "效果未知";
  gameState.player.items.splice(idx, 1);
  alert("你使用了" + (obj.name || obj) + "：" + result);
  render();
}

// 完成任务
function finishTask(idx) {
  let t = gameState.tasks[idx];
  if (!t.done) {
    t.done = true;
    addDiary("【勇闯任务】完成任务：" + t.name);
    if (!gameState.player.achievements.includes("任务达人")) {
      addAchievement("任务达人");
    }
    alert("任务完成！获得隐藏成就『任务达人』！");
    render();
  }
}

// 添加茶馆留言
function addTeahouseWall() {
  let msg = prompt("请输入你的爆料/吐槽：");
  if (msg && msg.trim()) {
    gameState.teahouseWall.push({msg: msg.trim(), ts: new Date().toLocaleTimeString()});
    render();
  }
}

// 押宝
function placeBet(optIdx) {
  let bet = gameState.teahouseBet;
  if (bet.result !== null) {
    alert("本局已开奖，请重置！");
    return;
  }
  const options = ["A", "B", "C"];
  bet.bets.push({name: gameState.player.nickname, opt: options[optIdx]});
  addDiary("在茶馆押宝：" + options[optIdx]);
  render();
}

// 开奖
function drawBet() {
  let bet = gameState.teahouseBet;
  if (bet.result !== null) {
    alert("已开奖！");
    return;
  }
  bet.result = Math.floor(Math.random() * 3);
  addDiary("茶馆押宝开奖：" + ["A", "B", "C"][bet.result]);
  render();
}

// 发送纸条
function sendNote() {
  let to = prompt("纸条要送给谁？（如：包子壮汉）");
  if (!to) return;
  let msg = prompt("写下你的纸条内容：");
  if (msg && msg.trim()) {
    let ts = new Date().toLocaleTimeString();
    gameState.teahouseNotes.push({to: to, msg: msg.trim(), ts: ts});
    addDiary("给" + to + "传纸条：" + msg.trim());
    render();
  }
}

// 生成存档
function generateSave() {
  gameState.saveCount++;
  gameState.lastSaveTurn = gameState.turn;
  
  const saveData = {
    gameState: JSON.parse(JSON.stringify(gameState)),
    timestamp: new Date().toLocaleString()
  };
  
  // 在实际应用中，这里可以保存到localStorage或服务器
  return JSON.stringify(saveData, null, 2);
}

// 检查是否需要存档
function checkAutoSave() {
  if (gameState.turn > 0 && gameState.turn % 5 === 0 && gameState.turn !== gameState.lastSaveTurn) {
    const saveData = generateSave();
    alert(`已自动生成存档 #${gameState.saveCount}\n请复制以下内容保存：\n\n${saveData}`);
  }
}

// 添加鸡肋系统状态
function addJileStatus() {
  if (gameState.player.jileStatus.length < 3) {
    const status = sysJilegEvents[Math.floor(Math.random() * sysJilegEvents.length)];
    if (!gameState.player.jileStatus.includes(status)) {
      gameState.player.jileStatus.push(status);
    }
  }
}

// 烹饪食物
function cookRecipe(recipeIdx) {
  const recipe = gameState.recipes[recipeIdx];
  let canCook = true;
  
  // 检查食材是否足够
  for (const ing of recipe.ingredients) {
    const item = gameState.cookingItems.find(i => i.name === ing);
    if (!item || item.qty <= 0) {
      canCook = false;
      break;
    }
  }
  
  if (canCook) {
    // 消耗食材
    for (const ing of recipe.ingredients) {
      const item = gameState.cookingItems.find(i => i.name === ing);
      item.qty--;
    }
    
    // 随机效果
    const healthGain = Math.floor(Math.random() * 10) + 5;
    const moodGain = Math.floor(Math.random() * 10) + 5;
    
    gameState.player.health = Math.min(100, gameState.player.health + healthGain);
    gameState.player.mood = Math.min(100, gameState.player.mood + moodGain);
    
    addDiary(`烹饪了${recipe.name}，恢复体力${healthGain}，心情${moodGain}`);
    alert(`成功烹饪${recipe.name}！恢复体力${healthGain}，心情${moodGain}`);
  } else {
    alert("食材不足，无法烹饪！");
  }
  render();
}

// 更新任务进度
function updateTaskProgress(taskIdx) {
  const task = gameState.tasks[taskIdx];
  if (!task.done) {
    task.progress++;
    if (task.progress >= task.maxProgress) {
      finishTask(taskIdx);
    }
    render();
  }
}

// 保存游戏
function saveGame() {
  const saveData = generateSave();
  gameState.saveSlots.push({
    id: gameState.saveSlots.length + 1,
    data: saveData,
    timestamp: new Date().toLocaleString(),
    turn: gameState.turn,
    location: gameState.player.location
  });
  alert(`游戏已保存到存档槽 #${gameState.saveSlots.length}`);
  render();
}

// 加载存档
function loadGame(slotIdx) {
  if (slotIdx >= 0 && slotIdx < gameState.saveSlots.length) {
    try {
      const saveData = JSON.parse(gameState.saveSlots[slotIdx].data);
      Object.assign(gameState, saveData.gameState);
      alert(`已加载存档 #${slotIdx + 1}`);
      render();
    } catch (e) {
      alert("加载存档失败！");
    }
  }
}

// 显示面板
function showPanel(type) {
  gameState.step = type;
  render();
}

// 显示NPC详情
function showNpcDetail(npcId) {
  gameState.step = "npcDetail_" + npcId;
  render();
}

// 步进
function goNext(dest) {
  gameState.step = dest;
  render();
}

// 佩戴成就
function equipAchievement(index) {
  const achievement = gameState.player.achievements[index];
  if (achievement) {
    gameState.player.equippedAchievement = achievement;
    addDiary("佩戴成就：" + achievement);
    render();
  }
}

// 佩戴称号
function equipTitle(index) {
  const title = gameState.player.titles[index];
  if (title) {
    gameState.player.equippedTitle = title;
    addDiary("佩戴称号：" + title);
    render();
  }
}

// 听书功能
function listenToStory() {
  const stories = [
    "话说那狗剩县有一奇人，能同时与三只狗对话，人称'狗语大师'！",
    "传闻县令夫人年轻时是江湖第一女侠，曾一人独战八大高手！",
    "城西包子铺老板其实是前朝御厨，因在包子馅里下诗被贬！",
    "昨晚有人看到神秘乞丐在月光下跳舞，舞姿比青楼头牌还妖娆！"
  ];
  
  const randomStory = stories[Math.floor(Math.random() * stories.length)];
  addDiary("在茶馆听书：" + randomStory);
  
  // 随机增加心情
  const moodGain = Math.floor(Math.random() * 10) + 5;
  gameState.player.mood = Math.min(100, gameState.player.mood + moodGain);
  
  alert("你听了一段精彩的评书：" + randomStory + "\n心情+" + moodGain);
  render();
}

// 赊账功能
function buyOnCredit() {
  const items = ["瓜子", "花生", "茶水", "点心"];
  const randomItem = items[Math.floor(Math.random() * items.length)];
  
  // 随机决定老板是否同意
  const success = Math.random() > 0.3;
  
  if (success) {
    addDiary("成功赊账买了" + randomItem);
    alert("老板同意你赊账买了" + randomItem + "！");
  } else {
    addDiary("赊账失败被赶出茶馆");
    alert("老板不同意赊账，把你赶出了茶馆！");
  }
  
  render();
}

function render(){
  const sc = document.getElementById('screen');
  let html = '';
  
  // 检查自动存档
  checkAutoSave();
  
  // 生成家族信息
  generateFamily();
  
  // 确保有成就
  if (gameState.player.achievements.length === 0) {
    addAchievement("穿越萌新");
    addTitle("社畜之光");
  }
  
  // 添加鸡肋状态
  addJileStatus();
  
  html += `<div class="scene-container">`;
  
  // —————欢迎页分幕————
  if(gameState.step=="welcome"){
    html += 
    `<div class="scene-content fade-in">
      <div class="card info-card" style="margin-top:29px">
        <div class="card-title">
        <span class="emj">✦</span>原创声明<span class="emj">✦</span></div>
        <div>《古代恶搞系统》作者：原如（小红书号306670937）
          <br>二传/倒卖替全站挡灾
          <br>美味厨房AI文游网站特供版
          <br>网址：misskey.meiweichufangai.com
          <br>免费分享，购买请维权
          <br>✦ 欢迎你魂穿古代！✦<br>
          <span class="emj">📲</span>请上传你的头像图片！</div>
      </div>
      <div class="player-card" style="margin-top:-10px">
        <div class="player-avatar-side">
          <div class="avatar-breathing pulse-anim">
            <img class="avatar-img" src="${gameState.player.avatar?gameState.player.avatar:'https://img2.baidu.com/it/u=1250141842,3354647410&fm=253&fmt=auto&app=138&f=JPEG?w=256&h=256'}" id="avatar-main">
          </div>
        </div>
        <div class="player-status-side" style="align-items:center;justify-content:center;">
          <button class="avatar-upload-btn" onclick="document.getElementById('file-selector').click()">导入头像</button>
        </div>
      </div>
      <div class="card zone2" style="text-align:center;">
        <span class="emj">✨</span>你是现代加班狗，某天猝死穿越。<br> <span style="color:#df8926;">点击下方"下一步"开始魂穿故事</span>
      </div>
    </div>
    <div class="scene-nav">
      <button class="nav-btn pulse-anim" onclick="goNext('chooseMusic')">下一步</button>
    </div>
    `;
  }
  // —————音频导入页————
  else if(gameState.step=="chooseMusic"){
    html +=
    `<div class="scene-content fade-in">
      <div class="card info-card"><div class="card-title">🎶 配乐导入</div>
        <div>你还可以选择一首音乐等待你在狗剩县混日子！<br>
        <button class="tool-btn" onclick="document.getElementById('music-selector').click()">导入音乐(mp3/m4a)</button>
        ${(gameState.musicUrl?`<div class="music-bar"><audio class="music-audio" controls loop autoplay src="${gameState.musicUrl}"></audio><span class='music-filename'>${(gameState.musicFile?gameState.musicFile.name:'')}</span></div>`:'')}
        </div>
      </div>
      <div class="card zone3" style="text-align:center;">
        <div>配乐可随时切换。准备好进入身份抽卡了吗？</div>
      </div>
    </div>
    <div class="scene-nav">
      <button class="nav-btn" onclick="goNext('welcome')">返回</button>
      <button class="nav-btn pulse-anim" onclick="goNext('identity')">抽取身份</button>
    </div>
    `;
  }
  // —————身份选择页————
  else if(gameState.step=="identity"){
    const randid = identityPool[Math.floor(Math.random()*identityPool.length)];
    gameState.player.identity=randid;
    gameState.player.skills = randid.skills.map(s=>Object.assign({},s));
    html += `
      <div class="scene-content fade-in">
        <div class="card info-card"><div class="card-title">🏷️ 随机初始身份</div>
        <div>前世：${randid.origin}<br>
        新身份：${randid.name}<br>
        <span style="font-size:.98em;color:#c26d11;">${randid.desc}</span>
        </div>
        </div>
        <div class="player-card">
          <div class="player-avatar-side">
            <div class="avatar-breathing">
              <img class="avatar-img" src="${gameState.player.avatar||'https://img2.baidu.com/it/u=1250141842,3354647410&fm=253&fmt=auto&app=138&f=JPEG?w=256&h=256'}">
            </div>
          </div>
          <div class="player-status-side" style="gap:5px">
            <div class="status-row"><span class="stat-label">身份：</span>${randid.name}</div>
            <div class="status-row"><span class="stat-label">技能：</span>${gameState.player.skills.map(s=>s.name).join('、')}</div>
            <div class="status-row"><span class="stat-label">标签：</span>${gameState.player.tags.join('、')}</div>
          </div>
        </div>
        <div class="card zone4" style="text-align:center;">
          <span class="emj">✨</span>准备进入魂穿剧情开场戏！<br>
        </div>
      </div>
      <div class="scene-nav">
        <button class="nav-btn" onclick="goNext('chooseMusic')">返回</button>
        <button class="nav-btn pulse-anim" onclick="goNext('main')">开始剧情</button>
      </div>
    `;
  }
  // —————主界面/主线剧情区────
  else if(gameState.step=="main" || gameState.step=="story"){
    // 当前剧情节点
    let sid = gameState.currentStoryId;
    let story = storyData[sid];
    // 玩家基础状态
    html += `
      <div class="scene-content fade-in">
        ${renderPlayerBlock()}
        <div class="main-story-card zone1">
          <div class="story-title">${story.title}</div>
          <span class="story-location"><span class="emj">🗺️</span>场景：${story.location}</span>
          <div class="story-sys">${renderSysJile()}</div>
          <div class="story-txt" id="main-story-text">${story.text.replace(/\n/g,"<br>")}</div>
          <div class="choices-list">
            ${story.options.map((op,i)=>{
              return `<button class="story-choice-btn" onclick="handleOptionClick('${i}')" id="choice-btn-${i}">${op.text}</button>`;
            }).join('')}
          </div>
        </div>
      </div>
      <div class="scene-nav">
        <button class="nav-btn" onclick="showPanel('viewInfo')">主控信息</button>
        <button class="nav-btn" onclick="showPanel('viewNPC')">NPC互动</button>
        <button class="nav-btn" onclick="showPanel('viewSystem')">系统</button>
      </div>
    `;
  }
  //——————主控详细信息页——————
  else if(gameState.step=="viewInfo"){
    html += `
      <div class="scene-content fade-in">
        ${renderPlayerBlock()}
        <div class="card zone3">
          <div class="card-title">主控详细档案</div>
          <div class="text-safe">
            <b>现身份：</b>${gameState.player.identity&&gameState.player.identity.name||'？'}
            <br><b>前世：</b>${gameState.player.identity&&gameState.player.identity.origin||''}
            <br>成就佩戴：${getTitle()}
            <br>标签：${gameState.player.tags.join('，')}
            <br>技能：${getPlayerSkillDesc()}
            <br><b>现有物品：</b>${(gameState.player.items.length==0)?"无":gameState.player.items.map(i=>i.name||i).join('、')}
          </div>
        </div>
        <div class="card zone4">
          <div class="card-title">血脉谱系树</div>
          <div class="text-safe">${gameState.player.family.length==0?"家谱：一人吃饱全家不饿":"家族成员：" + gameState.player.family.map(m => `<span class="family-member">${m}</span>`).join('')}</div>
        </div>
        <div class="card zone5"><div class="card-title">主控成就</div>
          <div class="achieve-list">${gameState.player.achievements.length==0?"暂无成就":gameState.player.achievements.map(ac=>`<span class="achieve-item">${ac}</span>`).join('')}</div>
        </div>
      </div>
      <div class="scene-nav">
        <button class="nav-btn" onclick="goNext('main')">返回</button>
        <button class="nav-btn" onclick="showPanel('viewTasks')">任务</button>
        <button class="nav-btn" onclick="showPanel('viewCooking')">烹饪</button>
      </div>
    `;
  }
  //——————NPC互动面板页——————
  else if(gameState.step=="viewNPC"){
    html += `
      <div class="scene-content fade-in">
        ${renderPlayerBlock()}
        <div class="card zone4">
          <div class="card-title">NPC关系和互动</div>
          <div class="scrollable-area">
            ${npcList.map(npc=>`
              <div class="npc-card" onclick="showNpcDetail(${npc.id})">
                <div class="npc-avatar">${npc.emoji}</div>
                <div class="npc-info">
                  <div class="npc-name">${npc.name}</div>
                  <div class="npc-mood">心情：${moodMap(npc.mood)} (好感${npc.relation}) 
                    <div class="npc-relation-bar"><div class="npc-relation-fill" style="width:${Math.min(100, Math.max(0, npc.relation))}%"></div></div>
                  </div>
                </div>
                <div class="npc-bubble">${npc.bubble}</div>
              </div>
            `).join('')}
          </div>
        </div>
        <div class="card zone6">
          <div class="card-title">🎭 NPC八卦</div>
          <div class="scrollable-area">
            <ul>
              ${gameState.npcGossip.map(gossip => `<li>${gossip}</li>`).join('')}
            </ul>
          </div>
        </div>
      </div>
      <div class="scene-nav">
        <button class="nav-btn" onclick="goNext('main')">返回</button>
        <button class="nav-btn" onclick="showPanel('viewTeahouse')">茶馆</button>
        <button class="nav-btn" onclick="showPanel('viewAchieve')">成就</button>
      </div>
    `;
  }
  //——————金手指（鸡肋系统）面板——————
  else if(gameState.step=="viewSystem"){
    html += `
      <div class="scene-content fade-in">
        ${renderPlayerBlock()}
        <div class="card zone6">
          <div class="card-title">🐔 鸡肋整蛊系统</div>
          <div>${renderSysJile(true)}</div>
        </div>
      </div>
      <div class="scene-nav">
        <button class="nav-btn" onclick="goNext('main')">返回</button>
        <button class="nav-btn" onclick="showPanel('viewBag')">背包</button>
        <button class="nav-btn" onclick="showPanel('viewDiary')">日记</button>
      </div>
    `;
  }
  //——————茶馆闲聊分区——————
  else if(gameState.step=="viewTeahouse"){
    html += `
      <div class="scene-content fade-in">
        ${renderPlayerBlock()}
        <div class="card zone5">
          <div class="card-title">⚱️ 古代生存茶馆</div>
          <div class="text-safe">
            <b>置顶规矩：</b><br>
            <ol class="teahouse-rules">
              <li>茶客不得动手打人，否则罚喝盐水！</li>
              <li>听书可插队，赊账必留姓名。</li>
              <li>匿名墙欢迎爆料，诽谤县令罚扫地。</li>
              <li>拼桌需自带瓜子，小气者禁入！</li>
              <li>押宝下注，输者请表演鸡叫跳舞！</li>
            </ol>
          </div>
          <div class="text-safe">
            <b>茶客一览：</b><br>
            NO.1 铁嘴张三<br>
            NO.2 神吐槽老李<br>
            NO.3 假正经赵四<br>
            NO.4 静静的翠花姐<br>
            NO.5 鸡毛掸子王五<br>
            NO.6 灶台八卦二丫<br>
            NO.7 戴花跑堂小胖<br>
            NO.8 不露脸的大黑狗<br>
            NO.9 傻乐书呆<br>
            NO.10 闪电女侠翠芝
          </div>
          <div class="text-safe"><b>近期话题：</b>
            ${gameState.teahouseTopics.map(topic => 
              `<div class="teahouse-topic">${topic}</div>`
            ).join('')}
          </div>
        </div>
      </div>
      <div class="scene-nav">
        <button class="nav-btn" onclick="goNext('main')">返回</button>
        <button class="nav-btn" onclick="showPanel('teahouseWall')">匿名墙</button>
        <button class="nav-btn" onclick="showPanel('teahouseBet')">押宝</button>
        <button class="nav-btn" onclick="listenToStory()">听书</button>
        <button class="nav-btn" onclick="buyOnCredit()">赊账</button>
      </div>
    `;
  }
  //——————成就称号区——————
  else if(gameState.step=="viewAchieve"){
    html += `
      <div class="scene-content fade-in">
        ${renderPlayerBlock()}
        <div class="card zone6">
          <div class="card-title">🏆 成就&称号系统</div>
          <div class="text-safe">
            <div>已获得成就：</div>
            <div class="achieve-list">${gameState.player.achievements.length==0?"暂无成就":gameState.player.achievements.map((a,i)=>
              `<span class="achieve-item">${a}${gameState.player.equippedAchievement === a ? ' ✅' : ''} 
              <button class="equip-btn" onclick="equipAchievement(${i})">佩戴</button></span>`
            ).join('')}</div>
            
            <div>当前佩戴成就：${gameState.player.equippedAchievement || '无'}</div>
            
            <div style="margin-top:15px;">已获得称号：</div>
            <div class="achieve-list">${gameState.player.titles.length==0?"暂无":gameState.player.titles.map((t,i)=>
              `<span class="achieve-item">${t}${gameState.player.equippedTitle === t ? ' ✅' : ''} 
              <button class="equip-btn" onclick="equipTitle(${i})">佩戴</button></span>`
            ).join('')}</div>
            
            <div>当前佩戴称号：${gameState.player.equippedTitle || '无'}</div>
            
            <div style="margin-top:7px;">Tips: 成就解锁后可在这里佩戴称号，获得社死光环！</div>
          </div>
        </div>
      </div>
      <div class="scene-nav">
        <button class="nav-btn" onclick="goNext('main')">返回</button>
        <button class="nav-btn" onclick="showPanel('viewSaves')">存档</button>
      </div>
    `;
  }
  //——————灶台烹饪板块———
  else if(gameState.step=="viewCooking"){
    html += `
      <div class="scene-content fade-in">
        ${renderPlayerBlock()}
        <div class="card zone7"><div class="card-title">🔥 古代灶台</div>
          <div class="text-safe"><b>现有食材：</b></div>
          <div style="display: flex; flex-wrap: wrap; gap: 8px; margin: 10px 0;">
            ${gameState.cookingItems.map(item => `
              <div style="background: #fff9e7; border: 1px solid #ffd796; border-radius: 8px; padding: 5px; min-width: 70px; text-align: center;">
                ${item.name} × ${item.qty}
              </div>
            `).join('')}
          </div>
          
          <div class="text-safe"><b>可选菜谱：</b></div>
          <div class="cooking-grid">
            ${gameState.recipes.map((recipe, idx) => `
              <div class="recipe-card">
                <div class="recipe-title">${recipe.name}</div>
                <div>需要: ${recipe.ingredients.join(', ')}</div>
                <div style="font-size:0.9em; margin-top:5px;">${recipe.desc}</div>
                <button class="tool-btn" style="margin-top:8px; width:100%;" onclick="cookRecipe(${idx})">烹饪</button>
              </div>
            `).join('')}
          </div>
        </div>
      </div>
      <div class="scene-nav">
        <button class="nav-btn" onclick="goNext('main')">返回</button>
      </div>
    `;
  }
  //——————背包板块————
  else if(gameState.step=="viewBag"){
    html += `
      <div class="scene-content fade-in">
        ${renderPlayerBlock()}
        <div class="card zone4">
          <div class="card-title">🎒 背包物品</div>
          <div class="text-safe">
            ${gameState.player.items && gameState.player.items.length ? 
              gameState.player.items.map((item,i)=>`
                <div style="display:flex;align-items:center;gap:10px;margin-bottom:5px;">
                  <span style="font-weight:bold">${item.name||item}</span>
                  ${item.desc?`<span style="color:#b37923">(${item.desc})</span>`:""}
                  ${item.use?`<button class="tool-btn" style="padding:1.5px 9px" onclick="useBagItem(${i})">使用</button>`:""}
                </div>
              `).join('') 
              : "你身无长物，身轻如燕~"}
          </div>
        </div>
      </div>
      <div class="scene-nav">
        <button class="nav-btn" onclick="goNext('main')">返回</button>
      </div>
    `;
  }
  //——————日记板块————
  else if(gameState.step=="viewDiary"){
    let logs = gameState.player.diary || [];
    html += `
      <div class="scene-content fade-in">
        ${renderPlayerBlock()}
        <div class="card zone5">
          <div class="card-title">📚 日常互动日记</div>
          <div class="scrollable-area">
            ${logs.length ? logs.map(d=>`<div style="font-size:0.97em;"><b>${d.ts}</b><br>${d.text}</div><hr style="margin:5px 0;border:0;border-top:1px solid #f7daaa;">`).join('') : "暂无日记。"}
          </div>
        </div>
      </div>
      <div class="scene-nav">
        <button class="nav-btn" onclick="goNext('main')">返回</button>
        <button class="nav-btn" onclick="addDiaryEntryPrompt()">写日记</button>
      </div>
    `;
  }
  //——————茶馆匿名墙————
  else if(gameState.step=="teahouseWall"){
    html += `
      <div class="scene-content fade-in">
        ${renderPlayerBlock()}
        <div class="card zone6">
          <div class="card-title">📝 匿名墙</div>
          <div class="scrollable-area">
            ${gameState.teahouseWall.length?gameState.teahouseWall.slice(-6).reverse().map(w=>`<div style="margin-bottom:7px;"><span style="color:#b07a1a">[匿名]</span> ${w.msg}</div>`).join(''):"暂无留言"}
          </div>
        </div>
      </div>
      <div class="scene-nav">
        <button class="nav-btn" onclick="showPanel('viewTeahouse')">返回</button>
        <button class="nav-btn" onclick="addTeahouseWall()">我要爆料</button>
      </div>
    `;
  }
  //——————茶馆押宝————
  else if(gameState.step=="teahouseBet"){
    let bet = gameState.teahouseBet;
    let options = [
      "A. 下一个进茶馆的人会踩狗屎",
      "B. 会被鸟屎砸中",
      "C. 会摔个大跟头"
    ];
    let betList = bet.bets.map(b=>`<li>${b.name||"你"} 押注：${b.opt}</li>`).join('');
    html += `
      <div class="scene-content fade-in">
        ${renderPlayerBlock()}
        <div class="card zone5">
          <div class="card-title">🎲 押宝区</div>
          <div class="text-safe">
            <b>今日押宝题：</b><br>
            <span style="color:#b07a1a">下一个进茶馆的人会发生什么？</span>
            <ul>${options.map((o,i)=>`<li>${o}</li>`).join('')}</ul>
            <div class="betting-grid">
              <div class="betting-option" onclick="placeBet(0)">押A</div>
              <div class="betting-option" onclick="placeBet(1)">押B</div>
              <div class="betting-option" onclick="placeBet(2)">押C</div>
            </div>
            <div><b>本局下注：</b><ul>${betList||"暂无"}</ul></div>
            ${bet.result!==null?`<div style="color:#c00;font-weight:bold;">开奖：${options[bet.result]}<br>${bet.bets.filter(b=>b.opt==options[bet.result][0]).length?"你中奖了！":"你没押中~"}</div>`:""}
          </div>
        </div>
      </div>
      <div class="scene-nav">
        <button class="nav-btn" onclick="showPanel('viewTeahouse')">返回</button>
        <button class="nav-btn" onclick="drawBet()">开奖</button>
      </div>
    `;
  }
  //——————任务系统————
  else if(gameState.step=="viewTasks"){
    html += `
      <div class="scene-content fade-in">
        ${renderPlayerBlock()}
        <div class="card zone5">
          <div class="card-title">📋 系统生存任务</div>
          <div class="task-board scrollable-area">
            ${gameState.tasks.map((task, idx) => `
              <div class="task-item">
                <input type="checkbox" class="task-checkbox" ${task.done ? 'checked' : ''} 
                  onclick="updateTaskProgress(${idx})" ${task.done ? 'disabled' : ''}>
                <div style="flex:1;">
                  <div class="${task.done ? 'task-done' : ''}">${task.name}</div>
                  <div style="font-size:0.9em; color:#a56813;">${task.desc}</div>
                  ${!task.done ? `
                    <div class="task-progress">
                      <div class="task-progress-fill" style="width:${(task.progress / task.maxProgress) * 100}%"></div>
                    </div>
                    <div>进度: ${task.progress}/${task.maxProgress}</div>
                  ` : ''}
                </div>
              </div>
            `).join('')}
          </div>
        </div>
      </div>
      <div class="scene-nav">
        <button class="nav-btn" onclick="goNext('main')">返回</button>
      </div>
    `;
  }
  //——————存档管理————
  else if(gameState.step=="viewSaves"){
    html += `
      <div class="scene-content fade-in">
        ${renderPlayerBlock()}
        <div class="card zone6">
          <div class="card-title">💾 存档管理</div>
          <div class="scrollable-area">
            <button class="tool-btn" style="width:100%; margin-bottom:15px;" onclick="saveGame()">新建存档</button>
            ${gameState.saveSlots.length > 0 ? 
              gameState.saveSlots.map((slot, idx) => `
                <div class="save-slot" onclick="loadGame(${idx})">
                  <div><b>存档 #${slot.id}</b></div>
                  <div class="save-info">时间: ${slot.timestamp}</div>
                  <div class="save-info">回合: ${slot.turn}</div>
                  <div class="save-info">地点: ${slot.location}</div>
                </div>
              `).join('') 
              : '<div style="text-align:center; padding:15px;">暂无存档</div>'}
          </div>
        </div>
      </div>
      <div class="scene-nav">
        <button class="nav-btn" onclick="goNext('main')">返回</button>
      </div>
    `;
  }
  //——————NPC详情页————
  else if(gameState.step.startsWith("npcDetail_")){
    const npcId = parseInt(gameState.step.split("_")[1]);
    const npc = npcList.find(n => n.id === npcId);
    
    if(npc){
      html += `
        <div class="scene-content fade-in">
          ${renderPlayerBlock()}
          <div class="card zone4">
            <div class="card-title">NPC详细信息</div>
            <div class="text-safe">
              <div style="text-align:center; margin-bottom:15px;">
                <div class="npc-avatar" style="width:80px;height:80px;margin:0 auto;">${npc.emoji}</div>
                <div style="font-size:1.2em; font-weight:bold; margin:10px 0;">${npc.name}</div>
              </div>
              
              <div><b>心情：</b> ${moodMap(npc.mood)}</div>
              <div><b>好感度：</b> ${npc.relation}</div>
              <div class="npc-relation-bar" style="margin:5px 0 15px 0;">
                <div class="npc-relation-fill" style="width:${Math.min(100, Math.max(0, npc.relation))}%"></div>
              </div>
              
              <div><b>位置：</b> ${npc.location}</div>
              <div><b>描述：</b> ${npc.desc}</div>
              <div><b>技能：</b> ${npc.skills.join(', ')}</div>
            </div>
          </div>
        </div>
        <div class="scene-nav">
          <button class="nav-btn" onclick="showPanel('viewNPC')">返回</button>
          <button class="nav-btn" onclick="addDiary('与${npc.name}进行了深入交流')">交流</button>
          <button class="nav-btn" onclick="addDiary('送给${npc.name}一个小礼物')">送礼</button>
        </div>
      `;
    }
  }
  //默认回主剧情
  else{
    gameState.step="main";render();return;
  }
  
  html += `</div>`;
  sc.innerHTML = html;
}

// 玩家黄金比例信息卡片
function renderPlayerBlock(){
  const p = gameState.player;
  function prog(val,lbl,icon,max=100){
    const percent = Math.min(100,Math.max(0,Math.floor(val/max*100)));
    return `
      <div class="status-row">
        <span class="stat-label">${icon}</span>
        <div class="stat-bar-wrap">
          <div class="stat-bar-bk"><div class="stat-bar-fill" style="width:${percent}%"></div></div>
        </div>
        <span style="font-weight:bold;color:#a36812;font-size:.98em;">${lbl(val)}</span>
      </div>
    `;
  }
  const avatarUrl = p.avatar || "https://img2.baidu.com/it/u=1250141842,3354647410&fm=253&fmt=auto&app=138&f=JPEG?w=256&h=256";
  return `
    <div class="player-card zone1" style="margin-top:0px;">
      <div class="player-avatar-side">
        <div class="avatar-breathing">
          <img class="avatar-img" src="${avatarUrl}">
        </div>
      </div>
      <div class="player-status-side">
        <div class="status-row" style="padding-bottom:3px;">
          <span class="stat-label">昵称：</span><span>${p.nickname}</span>
        </div>
        <div class="status-row" style="padding-bottom:3px;">
          <span class="stat-label">地点：</span><span>${p.location}</span>
        </div>
        <div class="status-row" style="padding-bottom:3px;">
          <span class="stat-label">时间：</span><span>${p.time}</span>
        </div>
        <div class="status-row" style="padding-bottom:3px;">
          <span class="stat-label">天气：</span><span>${p.weather}</span>
        </div>
        ${prog(p.mood, moodMap, "🤗")}
        ${prog(p.health, healthMap, "🌡️")}
        ${prog(p.luck, luckMap, "🍬")}
        ${prog(p.qiYun, v=>`${v}（气运）`, "☘️")}
      </div>
    </div>
  `;
}

// 处理剧情选项点击
function handleOptionClick(idx){
  const sid = gameState.currentStoryId;
  const story = storyData[sid];
  if(!story || !story.options[idx])return;
  
  // 属性变化
  if(story.options[idx].effects)
    Object.keys(story.options[idx].effects).forEach(k=>{
      if(typeof gameState.player[k]==='number') gameState.player[k]+=story.options[idx].effects[k];
      else if(typeof gameState.player[k]==='undefined') gameState.player[k]=story.options[idx].effects[k];
    });
  
  // 添加成就
  if(sid === "002a" && idx==0) {
    addAchievement("狗兄结拜");
    addTitle("狗奴");
    addBagItem(itemPool[3]); // 半只骨头
  }
  
  if(sid === "005a" && idx==0) {
    addAchievement("不挑食的好孩子");
  }
  
  // 下一剧情ID
  let nextId = story.options[idx].nextStoryId;
  if(storyData[nextId]){
    gameState.currentStoryId=nextId;
    gameState.step='story';
    gameState.turn+=1;
    render();
  }else{
    //如果无剧情，返回主界面
    gameState.step="main";
    render();
  }
  return;
}

// 添加日记条目
function addDiaryEntryPrompt(){
  let text = prompt("写下今日互动/吐槽：");
  if(text && text.trim()){
    addDiary(text.trim());
    render();
  }
}

// 头像文件input事件监听
document.getElementById('file-selector').addEventListener('change', function(e){
  if(this.files && this.files.length>0){
    handleAvatarUpload(this.files[0]);
  }
});

// 音乐文件input监听
document.getElementById('music-selector').addEventListener('change', function(e){
  if(this.files && this.files.length>0){
    gameState.musicFile = this.files[0];
    handleMusicUpload(this.files[0]);
  }
});

// 首次DOM加载
document.addEventListener("DOMContentLoaded", function(){
  render();
});

</script>
</body>
</html>